<template>  
    <div class="drawer">
      <el-drawer  v-model="drawer" size="80%" direction='ltr' title="上传全景图">

        <div class="container">
            <div class="container-header">
                <el-button :icon="Upload" type="primary"  @click="fileInput.click()" >全景图上传</el-button>
                <input type="file" style="display: none"  multiple ref='fileInput' @change="onFileChange" />
                <el-button :icon="Check" type="primary" @click="onSubmit" >开始上传</el-button>
            </div>
            
            <el-table :data="tableData" >
            <el-table-column prop="name" align="center" label="文件名" width="150" />
            <el-table-column prop="size" align="center" label="大小" width="150" />
            <el-table-column prop="progress" align="center" label="进度" width="240">
                <template #default="scope">
                <el-progress :percentage="scope.row.progress" />
                </template>
            </el-table-column>
            <el-table-column prop="progress" align="center" label="状态"  >
                <template #default="scope">
                <span :style="{color:tipColor(scope.row.uploadType)}">{{scope.row.uploadType == 4 ? scope.row.message : tip(scope.row.uploadType)}}</span>
                </template>
            </el-table-column>
            <el-table-column prop="progress" align="center" label="类型" width="150" >
                <template #default="scope">
                <el-select v-model="scope.row.type" placeholder="请选择" @change="onSelectChange(scope.$index,scope.row.type)">
                    <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                    />
                </el-select>
                </template>
            </el-table-column>
            <el-table-column prop="progress" align="center" label="操作" >
                <template #default="scope">
                <el-button size="small" type="danger"
                    @click="handleDelete(scope.$index, scope.row)"
                >
                    删除
                </el-button>
                </template>
            </el-table-column>
            </el-table>
        </div>
      
    </el-drawer>
    </div>
</template>
  
<script lang="ts" setup>
  import { ref,reactive,defineExpose } from 'vue'
  import { Upload, Check } from '@element-plus/icons-vue'
  import {upload} from '@/api/vr'
  import {useAccountStore} from '@/stores';
  const accountStore = useAccountStore()
  const fileInput = ref()
  const drawer = ref(false)
  
  const options = [{
    value: 1,
    label: '空中全景',
  },{
    value: 3,
    label: '地面全景',
  }]

  interface UploadImage {
    name: string,
    size: string,
    progress: number,
    type: number, //1|3,///1、空中全景 3、地面全景
    uploadType: number, //0|1|2|3,////0、开始上传 1、上传中 2、上传完成,3、图片大小不对
    message: string,
    file:File,
  }

  const tableData = reactive<UploadImage[]>([])

  const handleDelete = (index:number, row:UploadImage) => {
    console.log("删除了",index,row)
    tableData.splice(index,1)
  }
  const tip = (uploadType:number) => {
        if(uploadType == 0){
          return '准备上传';
        }else if(uploadType == 1){
          return '上传中...';
        }else if(uploadType == 2){
          return '上传完成';
        }else if(uploadType == 3){
          return '图片宽高比不对';
        }else if(uploadType == 4){
          return '上传失败';
        }
          return '';
    }
   const tipColor = (uploadType:number) => {
        if(uploadType == 2){
          return 'green';
        }else if(uploadType == 3){
          return 'red';
        }else if(uploadType == 4){
          return 'red'; 
        }
        return "gray"
   }
  const onSelectChange = (index:number,type:number)=>{
    console.log("index==",index,type)
    if(index != 0){return};
    for(let i = 0; i < tableData.length; i++) {
      tableData[i].type = type
    }
  }

////上传图片
const onFileChange = (e: Event) => {
    const files = (e.target as HTMLInputElement).files!;
    console.log("files===",files)

    for (let i = 0; i < files.length; i++) {
      let file = files[i];
      if (!file.type.startsWith('image/')) {
        return
      }

      let url = window.URL || window.webkitURL;
      let img = new Image();
      
      img.src = url.createObjectURL(file);
      
      img.onload = function () {
        var uploadType = 0;
        if (img.width / img.height != 2) {
          uploadType = 3
        }
        let item:UploadImage = {
          name: file.name,
          size: (file.size / 1000 / 1000).toFixed(2) + "M",
          progress: 0,
          type: 1,
          uploadType: uploadType,
          message: '',
          file: file
        } 
        tableData.push(item)
        
      }
    }
}

const onSubmit = async () => {
  const MAX_CONCURRENT_UPLOADS = 5;
  const pendingUploads = [...tableData].filter(item => item.uploadType === 0);
  const activeUploads = new Set();
  
  // 处理单个文件上传的函数
  const uploadFile = async (element: UploadImage) => {
    if (element.uploadType !== 0) return;
    
    const form = new FormData();
    form.append("file", element.file);
    form.append("type", element.type.toString());
    form.append("user_id", accountStore.account.user.id);

    try {
      const data = await upload(form, (progress: any) => {
        element.progress = progress.progress * 100;
        if (progress.uploadType !== 1) {
          element.uploadType = 1;
        }
      }) as any;

      if (data['code'] === 200) {
        element.uploadType = 2;
      } else {
        element.uploadType = 4;
        element.message = data['message'];
      }
    } catch (error) {
      element.uploadType = 4;
    } finally {
      activeUploads.delete(element);
      // 当有上传完成时，检查是否有待上传的文件
      if (pendingUploads.length > 0) {
        const nextFile = pendingUploads.shift();
        if (nextFile) {
          activeUploads.add(nextFile);
          uploadFile(nextFile);
        }
      }
    }
  };

  // 启动初始的上传任务
  while (activeUploads.size < MAX_CONCURRENT_UPLOADS && pendingUploads.length > 0) {
    const file = pendingUploads.shift();
    if (file) {
      activeUploads.add(file);
      uploadFile(file);
    }
  }
}

  const open = () => {
    drawer.value = true
 }
defineExpose({open})
</script>

<style scoped lang='scss'>
.drawer{
  background: red !important;
  :deep(.el-drawer){
    .el-drawer__title {
      font-size: 18px;
      font-weight: 600;
      color: #333333;
      margin-bottom: 0;
    }
    .el-drawer__header {
      margin-bottom: 0;
    }
    .el-drawer__body{
      padding: 15px 20px;
    }
  }
}
.container{
  height: 100% ;
  overflow-y: auto;
  :deep(.el-progress){
    .el-progress__text{
     display: none;
    }
  }
  &-header{
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    padding: 5px 10px;
    :deep(.el-button){
      box-shadow: none;
      border: none;
    }
  }
}


</style>
  